Diandiankong = {var_temperature:0, var_face_match:true, interval_id:[], run:false};


Blockly.Blocks['condtioner'] = {
  // y variable setter.
  init: function() {
    this.jsonInit({
      "message0": Blockly.Msg.DDK_CONDITIONER,
      "args0": [
        {
          "type": "input_value",
          "name": "temperature",
          "check": "Number"
        }
      ],
       "prevStatement": "Action",
       "nextStatement": "Action",
      "inputsInline": true,
      "colour": Blockly.Blocks.math.HUE,
      "helpUrl": Blockly.Msg.MATH_ARITHMETIC_HELPURL
    });
    this.setPreviousStatement(!0);
    // Assign 'this' to a variable for use in the tooltip closure below.
   
  }
};
Diandiankong.condtioner = function(temperature)
{
    document.getElementById("conditioner").style.color = "green";
    document.getElementById("conditioner_set").innerHTML  = temperature;
    setTimeout(function () {  
                 document.getElementById("conditioner").style.color = "";    
                }, 1000);  

}
Blockly.JavaScript['condtioner'] = function(block) {
  var temperature = Blockly.JavaScript.valueToCode(block, 'temperature',
      Blockly.JavaScript.ORDER_NONE) || '0';
 
  return 'Diandiankong.condtioner(' + temperature + ');\n';
};
Blockly.Blocks['open_door'] = {
  // y variable setter.
  init: function() {
    this.jsonInit({
      "message0": Blockly.Msg.DDK_OPENDOOR,
      
       "prevStatement": "Action",
       "nextStatement": "Action",
      "inputsInline": true,
      "colour": Blockly.Blocks.math.HUE,
      "helpUrl": Blockly.Msg.MATH_ARITHMETIC_HELPURL
    });
    this.setPreviousStatement(!0);
    // Assign 'this' to a variable for use in the tooltip closure below.
   
  }
};
Diandiankong.open_door = function()
{
    document.getElementById("door").style.color = "green";
    document.getElementById("door_op").innerHTML  = "开";
    setTimeout(function () {  
                 document.getElementById("door").style.color = "";    
    }, 1000); 
}
Blockly.JavaScript['open_door'] = function(block) { 
  return 'Diandiankong.open_door();\n';
};

Blockly.Blocks['close_door'] = {
  // y variable setter.
  init: function() {
    this.jsonInit({
      "message0": Blockly.Msg.DDK_CLOSEDOOR,
     
       "prevStatement": "Action",
       "nextStatement": "Action",
      "inputsInline": true,
      "colour": Blockly.Blocks.math.HUE,
      "helpUrl": Blockly.Msg.MATH_ARITHMETIC_HELPURL
    });
    this.setPreviousStatement(!0);
    // Assign 'this' to a variable for use in the tooltip closure below.
   
  }
};
Diandiankong.close_door = function()
{
   document.getElementById("door").style.color = "green";
    document.getElementById("door_op").innerHTML  = "关";
    setTimeout(function () {  
                 document.getElementById("door").style.color = "";    
    }, 1000); 
}
Blockly.JavaScript['close_door'] = function(block) { 
  return 'Diandiankong.close_door();\n';
};

Blockly.Blocks['temperature'] = {
  // y variable setter.
  init: function() {
    this.jsonInit({
	  "type": "temperature",
	  "message0": Blockly.Msg.DDK_TEMPERATURE ,
	   "output": "Number",
	  "colour": 120
	});
    // Assign 'this' to a variable for use in the tooltip closure below.
   
  }
};
Diandiankong.temperature = function(){
  
  console.log("temp: " + this.var_temperature);
  return this.var_temperature;
};

Blockly.JavaScript['temperature'] = function(block) { 
  var code =  'Diandiankong.temperature()';
  return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
};
Blockly.Blocks['face_match'] = {
  // y variable setter.
  init: function() {
    this.jsonInit({
	  "type": "face_match",
	  "message0": Blockly.Msg.DDK_FACEMATCH ,
	   "output": "Boolean",
	  "colour": 120
	});
    // Assign 'this' to a variable for use in the tooltip closure below.
   
  }
};
Diandiankong.face_match = function()
{
  return this.var_face_match;
}
Blockly.JavaScript['face_match'] = function(block) { 
  var code =  'Diandiankong.face_match()';
  return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];

};
Blockly.Blocks['win1'] = {
  // y variable setter.
  init: function() {
    this.jsonInit({
	  "type": "win1",
	  "message0": Blockly.Msg.DDK_WIN1 ,
	   "output": "Boolean",
	  "colour": 120
	});
    // Assign 'this' to a variable for use in the tooltip closure below.
   
  }
};
Diandiankong.win1 = function()
{
  return false;
}
Blockly.JavaScript['win1'] = function(block) { 
  var code =  'Diandiankong.win1()';
  return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];

};

Blockly.Blocks['win2'] = {
  // y variable setter.
  init: function() {
    this.jsonInit({
	  "type": "win1",
	  "message0": Blockly.Msg.DDK_WIN2 ,
	   "output": "Boolean",
	  "colour": 120
	});
    // Assign 'this' to a variable for use in the tooltip closure below.
   
  }
};
Diandiankong.win2 = function()
{
  return false;
}
Blockly.JavaScript['win2'] = function(block) { 
  var code =  'Diandiankong.win2()';
  return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
};
Blockly.Blocks['win3'] = {
  // y variable setter.
  init: function() {
    this.jsonInit({
	  "type": "win1",
	  "message0": Blockly.Msg.DDK_WIN3 ,
	   "output": "Boolean",
	  "colour": 120
	});
    // Assign 'this' to a variable for use in the tooltip closure below.
   
  }
};
Diandiankong.win3 = function()
{
    return false;
}
Blockly.JavaScript['win3'] = function(block) { 
  var code =  'Diandiankong.win3()';
  return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];

};

Blockly.Blocks['state_save'] = {
  // y variable setter.
  init: function() {
    this.jsonInit({
      "message0": Blockly.Msg.DDK_STATE_SAVE,
      "args0": [
        {
          "type": "input_value",
          "name": "win1",
          "check": "Boolean"
        },
		{
          "type": "input_value",
          "name": "win2",
          "check": "Boolean"
        },
        {
          "type": "input_value",
          "name": "win3",
          "check": "Boolean"
        }
      ],
       "prevStatement": "Action",
       "nextStatement": "Action",
      "inputsInline": false,
      "colour": Blockly.Blocks.math.HUE,
      "helpUrl": Blockly.Msg.MATH_ARITHMETIC_HELPURL
    });
    this.setPreviousStatement(!0);
    // Assign 'this' to a variable for use in the tooltip closure below.
   
  }
};

Diandiankong.state_save = function(win1, win2, win3)
{
  alert("存证成功");
}
Blockly.JavaScript['state_save'] = function(block) { 
  var win1 = false;
  var win2 = false;
  var win3 = false;
  win1 = Blockly.JavaScript.valueToCode(block, 'win1',
      Blockly.JavaScript.ORDER_NONE) || false;
  win2 = Blockly.JavaScript.valueToCode(block, 'win2',
      Blockly.JavaScript.ORDER_NONE) || false;
  win3 = Blockly.JavaScript.valueToCode(block, 'win3',
      Blockly.JavaScript.ORDER_NONE) || false;
 
  return 'Diandiankong.state_save(' + win1 +',' + win2 + ',' + win3+');\n';
};

var workspace = Blockly.inject('blocklyDiv',
        {media: './media/',
         toolbox: document.getElementById('toolbox')});  
Diandiankong.workspace = workspace;

 function showXml() {
          // Generate JavaScript code and display it.
          Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
          var xml = Blockly.Xml.workspaceToDom(Diandiankong.workspace);
          var data = Blockly.Xml.domToText(xml);
          alert(data);

  }

function showJsCode(){

          // Generate JavaScript code and display it.
          Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
          var code = Blockly.JavaScript.workspaceToCode(Diandiankong.workspace);

          alert(code);

  

}

function runCode() {
          // Generate JavaScript code and run it.
          window.LoopTrap = 1000;
          Blockly.JavaScript.INFINITE_LOOP_TRAP =
                  'if (--window.LoopTrap == 0) throw "Infinite loop.";\n';
          var code = "";
          code = Blockly.JavaScript.workspaceToCode(Diandiankong.workspace);
          Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
          try {
              eval(code);
              console.log(code);
         

          } catch (e) {
              alert(e);
   
          }
}  
function run() {
        document.getElementById('state').innerHTML = "正在执行";
        Diandiankong.interval_id.push( window.setInterval(function(){
        jQuery.ajax({
            type: 'POST',
            url: 'http://120.76.21.10:9080/api/device/tp/retrieve',
            //data: data_xml,
            success: function(response){
               console.log('here');
              var res = JSON.parse(response);
              console.log('ok:'+res.code +" message: " + res.message + " tp: " +res.result.tp);
              Diandiankong.var_temperature = res.result.tp;

              document.getElementById("temperature").style.color = "green";
              document.getElementById("temperature_span").innerHTML = Diandiankong.var_temperature;
              setTimeout(function () {  
                      document.getElementById("temperature").style.color = "";    
                      }, 1000); 
              runCode();
            },
            error: function(e){
              console.log('here2');
              var response = JSON.parse(e.responseText);
              console.log('err:'+response.code);
              console.log('err:'+response.message);
            },
            dataType: 'text'
          });
        }, 2000));
} 
function stop(){
  document.getElementById('state').innerHTML = "已经停止";
  for ( id in Diandiankong.interval_id){
    window.clearInterval(Diandiankong.interval_id[id]);
  }
  
}

function onchange()
{
    //runCode();
}
function upload() {
  var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
  var data_xml = Blockly.Xml.domToText(xml);
 jQuery.ajax({
	    type: 'POST',
	    url: 'http://120.76.21.10:9080/api/blockly/xml-parse',
	    data: data_xml,
	    success: function(response){
         console.log('here');
        var res = JSON.parse(response);
	      console.log('ok:'+res.code +" message: " + res.message);
	      
	    },
	    error: function(e){
        console.log('here2');
	      var response = JSON.parse(e.responseText);
	      console.log('err:'+response.code);
        console.log('err:'+response.message);
	    },
	    dataType: 'text'
	  });
};

function load_it() {
  var loadInput = document.getElementById('load');
  loadInput.addEventListener('change', load, false);

  loadInput.click();
};
function save() {
          var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
          var data = Blockly.Xml.domToText(xml);
          s = prompt("Enter file name","block.xml");

          var blob = new Blob([data], {type: "text/plain;charset=utf-8"});
          saveAs(blob, s);
};
function load() {
  var event = arguments[0]||window.event;
  var files = event.target.files;
  // Only allow uploading one file.
  if (files.length != 1) {
      return;
  };

  // FileReader
  var reader = new FileReader();
  reader.onloadend = function(event) {
      var target = event.target;
      // 2 == FileReader.DONE
      if (target.readyState == 2) {
          try {
              var xml = Blockly.Xml.textToDom(target.result);
          } catch (e) {
              alert('Error parsing XML:\n' + e);
              return;
          }
          var count = Blockly.mainWorkspace.getAllBlocks().length;
          if (count && confirm('Replace existing blocks?\n"Cancel" will merge.')) {
              Blockly.mainWorkspace.clear();
          }
          Blockly.Xml.domToWorkspace(xml, Blockly.mainWorkspace);
      }
      // Reset value of input after loading because Chrome will not fire
      // a 'change' event if the same file is loaded again.
      document.getElementById('load').value = '';
  };
  reader.readAsText(files[0]);

};
 Diandiankong.workspace.addChangeListener(onchange);

 jQuery(function($){
    
    });